//
//  CLocationManager.m
//  JKServer
//
//  Created by 丁攀 on 2017/12/8.
//  Copyright © 2017年 Facebook. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "CLocationManager.h"
#import <React/RCTLog.h>
#import <React/RCTConvert.h>


@interface CLocationManager () <AMapLocationManagerDelegate>
@end

@implementation CLocationManager


// To export a module named CalendarManager
RCT_EXPORT_MODULE();


// This would name the module AwesomeCalendarManager instead
// RCT_EXPORT_MODULE(AwesomeCalendarManager);

// RCT_EXPORT_METHOD(getPosition:(NSString *)name location:(NSString *)location)
// {
//   RCTLogInfo(@"Pretending to create an event %@ at %@", name, location);
// }
RCT_REMAP_METHOD(getPosition,
                 resolver:(RCTPromiseResolveBlock)resolve
                 rejecter:(RCTPromiseRejectBlock)reject)
{
  self.locationManager = [[AMapLocationManager alloc] init];
  //设置期望定位精度
  [self.locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
  self.locationManager.locationTimeout =2;
  //   逆地理请求超时时间，最低2s，此处设置为2s
  self.locationManager.reGeocodeTimeout = 2;
  [self.locationManager requestLocationWithReGeocode:YES completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
    if (error) {
      //NSString *name = @"locError:{%ld - %@};", (long)error.code, error.localizedDescription);
      //NSString *desc = error.localizedDescription;
      //NSError *cerror = error;
      reject(@"locError", @"AmapError", error);
      /**
      if (error.code == AMapLocationErrorLocateFailed)
      {
        return;
      }**/
    } else {
      if(!regeocode.city) {
        reject(@"locError", @"AmapError", nil);
      } else {
        NSDictionary *result = @{
                                 @"city": regeocode.city,
                                 @"aoi": regeocode.AOIName ?: [NSNull null],
                                 @"address": regeocode.formattedAddress,
                                 @"longitude": [NSNumber numberWithDouble:location.coordinate.longitude],
                                 @"latitude": [NSNumber numberWithDouble:location.coordinate.latitude],
                                 @"citycode": regeocode.citycode,
                                 @"adcode": regeocode.adcode
                                 };
        resolve(result);
      }
      //NSString *result = location;

      //reject(@"locError", @"AmapError", error);
    }
    /**
    NSLog(@"location:%@", location);
    
    if (regeocode)
    {
      NSLog(@"reGeocode:%@", regeocode);
    }
     **/
  }];
}


@end
